package DesginFotmat;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class OutputInturn2 {
    public static void main(String[] args) {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();
        new Thread(() -> {
            awaitSignal.print("a",a,b);
        },"t1").start();

        new Thread(() -> {
            awaitSignal.print("b",b,c);
        },"t2").start();

        new Thread(() -> {
            awaitSignal.print("c",c,a);
        },"t3").start();

        awaitSignal.lock();
        try{
            a.signal();
        }finally {
            awaitSignal.unlock();
        }
    }
}

class AwaitSignal extends ReentrantLock{
    private int loopNumber;
    public AwaitSignal(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    //参数1打印内容，参数2进入哪一间休息室,参数3下一间休息室
    public void print(String str, Condition current, Condition next) {
        for (int i = 0; i < loopNumber; i++) {
            lock();
            try{
                current.await();
                System.out.println(str);
                next.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                unlock();
            }
        }
    }
}
